package yz.cp.back.websocket.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import yz.cp.back.auth.oauth.token.MyRedisTokenStore;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.common.res.ApiException;
import yz.cp.back.websocket.service.ITokenService;

import java.security.Principal;

/**
 * Created by xukangkang on 2019/3/18.
 */
@Service
public class TokenService implements ITokenService {
    @Autowired
    private MyRedisTokenStore redisTokenStore;

    @Override
    public SecUser retrieveUser(String accessToken) {
        try {
            Principal principal = redisTokenStore.readAuthentication(accessToken);
            OAuth2Authentication OAuth2Authentication = (OAuth2Authentication) principal;
            Object object = OAuth2Authentication.getUserAuthentication().getPrincipal();
            if (object instanceof SecUser) {
                SecUser user = (SecUser) object;
                return user;
            } else {
                throw new ApiException("获取用户失败");
            }
        } catch (Exception e) {
            throw new ApiException("获取用户失败");
        }
    }

    @Override
    public OAuth2Authentication retrieveUserPrincipal(String accessToken) {
        try {
            Principal principal = redisTokenStore.readAuthentication(accessToken);
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
            Object object = oAuth2Authentication.getUserAuthentication().getPrincipal();
            if (object instanceof SecUser) {
                return oAuth2Authentication;
            } else {
                throw new ApiException("获取用户失败");
            }
        } catch (Exception e) {
            throw new ApiException("获取用户失败");
        }
    }
}
